package com.sxfq.loansupermarket.backsystem.modular.basicData.controller;

import com.sxfq.loansupermarket.backsystem.common.annotion.log.BussinessLog;
import com.sxfq.loansupermarket.backsystem.common.constant.Dict;
import com.sxfq.loansupermarket.backsystem.common.constant.factory.ConstantFactory;
import com.sxfq.loansupermarket.backsystem.common.controller.BaseController;
import com.sxfq.loansupermarket.backsystem.common.exception.BizExceptionEnum;
import com.sxfq.loansupermarket.backsystem.common.exception.BussinessException;
import com.sxfq.loansupermarket.backsystem.common.node.ZTreeNode;
import com.sxfq.loansupermarket.backsystem.common.persistence.dao.MChannelMapper;
import com.sxfq.loansupermarket.backsystem.common.persistence.model.Channel;
import com.sxfq.loansupermarket.backsystem.core.log.LogManager;
import com.sxfq.loansupermarket.backsystem.core.log.LogObjectHolder;
import com.sxfq.loansupermarket.backsystem.core.log.factory.LogTaskFactory;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.support.HttpKit;
import com.sxfq.loansupermarket.backsystem.core.util.ToolUtil;
import com.sxfq.loansupermarket.backsystem.modular.basicData.dao.ChannelDao;
import com.sxfq.loansupermarket.backsystem.modular.basicData.entity.ChannelInfo;
import com.sxfq.loansupermarket.backsystem.modular.basicData.service.IChannelService;
import com.sxfq.loansupermarket.backsystem.modular.system.warpper.ChannelWarpper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 渠道控制器
 *
 * @author fengshuonan
 * @Date 2017年2月17日20:27:22
 */
@Controller
@RequestMapping("/channel")
public class ChannelController extends BaseController {

    @Resource
    ChannelDao channelDao;
    @Autowired
    private RedisTemplate redisTemplate;
    @Resource
    MChannelMapper mchannelMapper;

    @Resource
    IChannelService channelService;

    private String PREFIX = "/basicData/channel/";

    /**
     * 跳转到渠道管理首页
     */
    @RequestMapping("")
    public String index() {
        String tableHead = redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"Abbreviation",0)+"";
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        return PREFIX + "channel.html";
    }

    /**
     * 跳转到添加渠道
     */
    @RequestMapping("/channel_add")
    public String channelAdd() {
        String tableHead = redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"Abbreviation",0)+"";
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        return PREFIX + "channel_add.html";
    }

    /**
     * 最大渠道审核级别
     */
    @RequestMapping("/to_maxChannelauditLevel")
    public String to_maxChannelauditLevel(Model model) {
        String tableHead = redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"Abbreviation",0)+"";
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        ChannelInfo channelInfo = channelService.getMaxChannelAudiLevel();
        model.addAttribute("channelInfo", channelInfo);
        return PREFIX + "max_channel_audit_level.html";
    }

    @RequestMapping(value = "/editMaxLevelSubmit", method = RequestMethod.POST)
    @ResponseBody
    public int editMaxLevelSubmit(String id, String maxLevel, String remarks, Model model) throws Exception {
        return channelService.updateMaxChannelAudiLevel(id, maxLevel, remarks);
    }

    @RequestMapping("/channel_update/{channelId}")
    public String channelUpdate(@PathVariable Integer channelId, Model model) {
        String tableHead = redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"Abbreviation",0)+"";
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        Channel channel = mchannelMapper.selectById(channelId);
        model.addAttribute(channel);
        model.addAttribute("cName", ConstantFactory.me().getchannelName(channel.getPid()));
        LogObjectHolder.me().set(channel);
        return PREFIX + "channel_edit.html";
    }

    /**
     * 获取渠道的tree列表
     */
    @RequestMapping(value = "/tree")
    @ResponseBody
    public List<ZTreeNode> tree() {
        List<ZTreeNode> tree = this.channelDao.tree();
        tree.add(ZTreeNode.createParent());
        return tree;
    }

    /**
     * 新增渠道
     */
    @BussinessLog(value = "添加渠道", key = "channelName", dict = Dict.ChannelDict)
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(Channel channel) {
        if (ToolUtil.isOneEmpty(channel, channel.getChannelname())) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        channelSetPids(channel);//完善pids,根据pid拿到pid的pids
        return this.mchannelMapper.insert(channel);
    }

    /**
     * 获取所有渠道列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String condition) {
        List<Map<String, Object>> list = this.channelDao.list(condition);
        return super.warpObject(new ChannelWarpper(list));
    }

    /**
     * 渠道详情
     */
    @RequestMapping(value = "/detail/{channelId}")
    @ResponseBody
    public Object detail(@PathVariable("channelId") Integer channelId) {
        return mchannelMapper.selectById(channelId);
    }

    /**
     * 修改渠道
     */
    @BussinessLog(value = "修改渠道", key = "simplename", dict = Dict.ChannelDict)
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(Channel channel) {
        if (ToolUtil.isEmpty(channel) || channel.getId() == null) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        channelSetPids(channel);
        mchannelMapper.updateById(channel);
        return super.SUCCESS_TIP;
    }

    /**
     * 删除渠道
     */
    @BussinessLog(value = "删除渠道", key = "channelId", dict = Dict.DeleteDict)
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer channelId) {
        LogObjectHolder.me().set(ConstantFactory.me().getchannelName(channelId));//缓存被删除的渠道名称
        channelService.deleteChannel(channelId);
        return SUCCESS_TIP;
    }

    private void channelSetPids(Channel channel) {
        if (ToolUtil.isEmpty(channel.getPid()) || "0".equals(channel.getPid() + "")) {
            channel.setPid(0);
            channel.setPids("[0],");
        } else {
            int pid = channel.getPid();
            Channel temp = mchannelMapper.selectById(pid);
            String pids = temp.getPids();
            channel.setPid(pid);
            channel.setPids(pids + "[" + pid + "],");
        }
    }

    @RequestMapping(value = "/getChannel", method = RequestMethod.POST)
    @ResponseBody
    public List<Map<String, Object>> getChannel() {
        if (ShiroKit.getSessionAttr("channelList") == null) {
            ShiroKit.setSessionAttr("channelList", channelService.getChannel());
            return ShiroKit.getSessionAttr("channelList");
        } else {
            return ShiroKit.getSessionAttr("channelList");
        }
    }

    @RequestMapping(value = "/getChannels", method = RequestMethod.POST)
    @ResponseBody
    public List<Map<String, Object>> getChannels() {
        if (ShiroKit.getSessionAttr("channelLists") == null) {
            ShiroKit.setSessionAttr("channelLists", channelService.getChannels());
            return ShiroKit.getSessionAttr("channelLists");
        } else {
            return ShiroKit.getSessionAttr("channelLists");
        }
    }

    @RequestMapping(value = "/getChannelss", method = RequestMethod.POST)
    @ResponseBody
    public List<Map<String, Object>> getChannelss() {
        if (ShiroKit.getSessionAttr("channelListss") == null) {
            ShiroKit.setSessionAttr("channelListss", channelService.getChannelss());
            return ShiroKit.getSessionAttr("channelListss");
        } else {
            return ShiroKit.getSessionAttr("channelListss");
        }
    }

    @RequestMapping(value = "/getChannelssd", method = RequestMethod.POST)
    @ResponseBody
    public List<Map<String, Object>> getChannelssd() {
        if (ShiroKit.getSessionAttr("channelListssd") == null) {
            ShiroKit.setSessionAttr("channelListssd", channelService.getChannelssd());
            return ShiroKit.getSessionAttr("channelListssd");
        } else {
            return ShiroKit.getSessionAttr("channelListssd");
        }
    }

    @RequestMapping(value = "/getChannelsss", method = RequestMethod.POST)
    @ResponseBody
    public List<Map<String, Object>> getChannelsss() {
        if (ShiroKit.getSessionAttr("channelListsss") == null) {
            ShiroKit.setSessionAttr("channelListsss", channelService.getChannelsss());
            return ShiroKit.getSessionAttr("channelListsss");
        } else {
            return ShiroKit.getSessionAttr("channelListsss");
        }
    }
}